import React from 'react'
import _ from 'underscore'
import $ from 'jquery'

import {Scope} from 'lib/scopeFactory'
import TimeStore from 'lib/stores/time-store'
import traceDetail from '../apis/traceDetail'
import {tracelistApi,createGridOrder,parseToPartGrid} from '../apis/tracelist'
import {coreApi,sortMap,parseToChart} from '../apis/core-util'
import {parseToGrid,parseToGrid2} from '../apis/tracelist'
import format from 'lib/util/format'

export default class TraceScope extends Scope {
  constructor(props){
    // debugger
    super(props);
    this.traceType = props.routeParams.traceType // crashlog,webview,anr
    this.appVersionId = props.routeParams.appVersionId
    this.deviceId = props.routeParams.deviceId
    this.userIdentifier = decodeURIComponent(props.routeParams.userIdentifier)
    this.dataType = props.routeParams.dataType?props.routeParams.dataType:'nodata' // jsError,ajaxError,ajaxTrace; undefined
    // 1:androidCrash,2:iosCrash,5:jsError,7:ajaxError,8:ajaxTrace
    this.param1 = props.routeParams.param1 // :crashNameId, :domainId
    this.param2 = props.routeParams.param2 // undefined, :urlId
    if (this.param1 && !this.param2) {
      this.dataType = this.param1
    }

    this.$state = {
      titleSuffix:(this.traceType==='crashlog'?' - 崩溃轨迹':(this.traceType==='webview'?' - webview异常':' - ANR')),
      trace:null,
      traceType:this.traceType,
      dataType:this.dataType,
      grid:{
        loading:true,
        // getOrder:createGridOrder('timestamp',-1)
      },
      crashGrid:{
        loading:true,
        getOrder:createGridOrder('count', -1)
        // getOrder:createGridOrder('appVersion', -1)
      },
      jsErrorGrid:{
        loading:true,
        // getOrder:createGridOrder('timestamp', -1)
        getOrder:createGridOrder('appVersion', -1)
      },
      ajaxGrid:{
        loading:true,
        getOrder:createGridOrder('timestamp', -1)
      },
      ajaxCols:[
        {
          title:'域名',
          key:'domain'
        },
        {
          title:'请求名称',
          key:'url',
          render:(url,rowData)=>(
            <a href={BlueWare.pageUrlPrefix+'/app/'+BlueWare.appId+'/ajax'+'#/domain/'+rowData.domainId+'/url/'+rowData.urlId+'/'+rowData.ajaxTraceType+'/'+this.requestTime}>
              {url}
            </a>
          )
        },
        {
          title:'平均耗时',
          key:'avg',
          // sortable:true,
          formatter:format.numSecs
        },
        {
          title:'采集次数',
          key:'count',
          // sortable:true,
          format:format.integer
        },
        // {
        //   title:'影响用户数',
        //   key:'affected',
        //   sortable:true,
        //   format:format.integer
        // },
        {
          title:'最近采集时间',
          key:'lastTime',
          formatter:format.stampToTime
        }
      ]
    }

    this.traceApiParams = {
      urlName:'custom/user_summary',
      // urlName:BlueWare.platform.toLowerCase()+'_crash_extra_data',
      userIdentifier:this.userIdentifier,
      dataType:BlueWare.platform.toLowerCase()==='android'?1:2,
      appVersionId:this.appVersionId,
      deviceId:this.deviceId
    }
    this.crashlogGridApiParams = {
      // classify:'crashname',
      urlName:'custom/crash',
      // urlName:BlueWare.platform.toLowerCase()+'_crash_improved_data',
      // viewKey:'crash_count',
      // order:'301',
      // size:1,
      appVersionId:this.appVersionId,
      deviceId:this.deviceId,
      userIdentifier:this.userIdentifier,
      dataType:BlueWare.platform.toLowerCase()==='android'?1:2,
      limit:10,
      // order:'appVersion',
      // orderModel:'desc'
    }
    this.jserrorGridApiParams = {
      urlName:'custom/js',
      appVersionId:this.appVersionId,
      userIdentifier:this.userIdentifier,
      classify:'jsurlmsg',
      // osId:'',
      // osVersionId:'',
      // nameId:'',
      // offset:'',
      limit:10,
      deviceId:this.deviceId
      // order:503
    }
    this.ajaxGridApiParams = {
      urlName:'custom/ajax',
      appVersionId:this.appVersionId,
      deviceId:this.deviceId,
      userIdentifier:this.userIdentifier,
      dataType:this.dataType.toLowerCase()==='ajaxerror'?1:2, // ajaxError,ajaxTrace
      //offset:'',
      limit:10,
      //order:'appVersion',
      //orderModel:'desc'
    }

    // update params
    if (this.traceType === 'crashlog') {
      // for crashlog
      if (this.param1) {
        this.traceApiParams = _.extend(this.traceApiParams, {
          dataType: BlueWare.platform.toLowerCase()==='android'?1:2,
          crashNameId: this.param1
        })
        this.crashlogGridApiParams = _.extend(this.crashlogGridApiParams, {crashNameId: this.param1})
      }
    }
    else if (this.traceType === 'webview') {
      // for ajax
      if (this.dataType.indexOf('ajax') !== -1) {
        if (this.param1 && this.param2) {
          this.traceApiParams = _.extend(this.traceApiParams, {
            dataType: this.dataType.toLowerCase() === 'ajaxerror'?7:8,
            domainId: this.param1,
            urlId: this.param2
          })
          this.ajaxGridApiParams = _.extend(this.ajaxGridApiParams, {
            domainId: this.param1,
            urlId: this.param2
          })
        }
        else {
          this.traceApiParams = _.extend(this.traceApiParams, {
            dataType: this.dataType.toLowerCase() === 'ajaxerror'?7:8
          })
        }
      }
      // for jsError
      else if (this.dataType.indexOf('js') !== -1) {
        this.traceApiParams = _.extend(this.traceApiParams, {
          dataType: 5
        })
      }

    }
    // else {
    //   this.traceApiParams = _.extend(this.traceApiParams, {
    //     dataType: 5
    //   })
    // }

    this.traceApi = traceDetail(this.traceApiParams,TimeStore.getValue)

    // this.crashlogGridApi = tracelistApi(this.crashlogGridApiParams,TimeStore.getValue)
    this.crashlogGridApi = tracelistApi(this.crashlogGridApiParams,TimeStore.getValue,this.$state.crashGrid.getOrder)

    // this.jserrorGridApi = tracelistApi(this.jserrorGridApiParams,TimeStore.getValue)
    this.jserrorGridApi = tracelistApi(this.jserrorGridApiParams,TimeStore.getValue,this.$state.jsErrorGrid.getOrder)

    this.ajaxGridApi = tracelistApi(this.ajaxGridApiParams,TimeStore.getValue,() => this.requestTime,this.$state.ajaxGrid.getOrder)

  }

  fetch(){
    var _this = this;
    this.requestTime = Date.now();

    this.traceApi.fetch().then((rawData,params) => {
      this.$state.trace = rawData.data
      if(rawData.data.extraDatas){
        this.$state.extraDatas = JSON.parse(rawData.data.extraDatas)
      }
      this.emit()
    });

    //debugger
    //console.log(this)
    if (this.traceType==='crashlog') {
      this.crashlogGridApi.fetch().then(function(rawData,params){
        _this.$state.crashGrid = parseToPartGrid(rawData,params)
        // _this.$state.grid = parseToPartGrid(rawData,params)
      },function(err){
        _this.$state.crashGrid = {
          error:err
        }
      },function(params){
        _this.$state.crashGrid = {
          loading:true,
          params:params
        }
        _this.emit()
      }).always(function(){
        _this.emit()
      })
    }
    else if (this.traceType==='webview') {
      if (this.dataType==='jsError') {
        this.jserrorGridApi.fetch().then(function(rawData,params){
          _this.$state.jsErrorGrid = parseToPartGrid(rawData,params)
          // _this.$state.grid = parseToGrid(rawData.data,params)
        },function(err){
          _this.$state.jsErrorGrid = {
            error:err
          }
        },function(params){
          _this.$state.jsErrorGrid = {
            loading:true,
            params:params
          }
          _this.emit()
        })
        .always(function(){
          _this.emit()
        })
      }
      else {
        this.ajaxGridApi.fetch().then(function(rawData,params){
          //console.log(rawData)
          //console.log(_this.dataType)
          _this.$state.ajaxGrid = parseToGrid2(_.map(rawData, item => {
            item.ajaxTraceType = _this.dataType.toLowerCase()==='ajaxerror'?'error':'slow';
            return item
          }), params, p => {
            _.map(p, i => {
              i['ajaxTraceType'] = _this.dataType.toLowerCase()==='ajaxerror'?'error':'slow';
              return i;
            })
          })
        },function(err){
          _this.$state.ajaxGrid = {
            error:err
          }
        },function(params){
          _this.$state.ajaxGrid = {
            loading:true,
            params:params
          }
          _this.emit()
        })
          .always(function(){
            _this.emit()
          })
        }
      }

    }

  $settime(){
    this.fetch()
  }

  $load(){
    this.fetch();
  }
}
